<?php

namespace app\admin\controller;

use app\admin\controller\Common;
use think\Db;

class File extends Common
{

    public function index()
    {
        $where = [];
        $field = input('get.field', '');
        $value = input('get.value', '');
        $search_field = input('get.search_field', '');
        $search_value = input('get.search_value', '');
        $date_range = input('get.date_range', '');

        if ($field && $value) $where[] = [$field, 'eq', $value];
        if ($search_field && $search_value) $where[] = [$search_field, 'eq', $search_value];


        $name = [];
        $start_time = $end_time = '';
        if (!empty($date_range)) {
            $date_range = explode(' - ', $date_range);
            $start_time = strtotime($date_range[0]);
            $end_time = strtotime($date_range[1]) + 86399;
            $name['begin_date'] = $date_range[0];
            $name['end_date'] = $date_range[1];
        }
        if (!(empty($start_time)) && !(empty($end_time))) {
            $where[] = ['f.create_time', 'egt', $start_time];
            $where[] = ['f.create_time', 'elt', $end_time];
        }


        $fileModel = model('common/member/File');
        $data = [
            'type' => $fileModel::TYPE,
            'status' => $fileModel::STATUS,
            'list' => $fileModel->getFileList($where, 'f.*, m.nickname,m.username,m.real_verify', 'f.create_time desc')
        ];
        $this->assign('data', $data);
        $this->assign('page', $fileModel->page_info->render());
        $this->assign('name', $name);

        return $this->fetch();
    }

    public function del()
    {
        $fileModel = model('common/member/File');
        if ($this->request->isAjax()) {
            $id = input('post.id/d', '');
            if (!$id) {
                return ['err' => '缺少必要参数'];
            }
            $file = $fileModel->getInfo(['id' => $id]);
            if (empty($file)) {
                return ['err' => '文件不存在'];
            }
            $isDel = $fileModel->delByID($id);
            if (!$isDel) {
                return ['err' => '删除失败，请重试'];
            }
//            $file_path = ROOT_PATH . 'public' . $file['url'];
            $fileLogic = model('common/file/FileLogic', 'logic');
            if ($fileLogic->fileExists($file['url'])) $fileLogic->deleteFile($file['url']);
            return ['ret' => '删除成功'];
        }
        return ['err' => '请求方式有误'];
    }

    public function uploadImages()
    {
        if ($file = $this->request->file('file')) {
            $fileDir = ROOT_PATH . 'public' . DS . 'disk' . DS . input('get.path', 'upload');
            if (!file_exists($fileDir)) {
                mkdir($fileDir, 0755, true);
            }
            $info = $file->validate(['ext' => 'jpg,png,gif,jpeg'])->move($fileDir);
            if ($info) {

                $data = [
                    'img' => str_replace(ROOT_PATH . 'public', '', $fileDir) . DS . $info->getSaveName(),
                    'text' => ''
                ];
                $data['imgurl'] = $data['img'];
                $data['id'] = model('common/member/File')->add([
                    'type' => input('get.fileType/d', 0),
                    'url' => $data['img'],
                    'create_time' => time()
                ]);


                //加水印
                $realPath = ROOT_PATH . DS . 'public' . DS . $data['img'];
                $image = \think\Image::open($realPath);
                // 给原图左上角添加水印并保存water_image.png
                $image->water(ROOT_PATH . DS . 'public' . config('app.fixed_image_path.water_image'), \think\Image::WATER_SOUTHEAST)->save($realPath);

                return json($data);
            } else {
                return json(['err' => $file->getError()]);
            }


        }
        return json(['err' => '请选择文件']);
    }


    /**
     * User: Simony
     * Function:发送客服图片
     */
    public function sendCustomerServiceImg()
    {
        //params
        $file = request()->file('file'); //表单提交
        $target = input('param.target/d', 6); //接收消息用户id

        //operate
        $file_info = $file->getInfo();
        $filename = $file_info['name'];


        $platform = sysConfig('platform');
        $ext = model('common/member/Member')->getInfoByID($platform['customer_service_member_id'] ?? 1, 'nickname,avatar');
        if (!$ext) return;
        $ext = $ext->toArray();
        $ext['type'] = 1;
        $ext['isBurned'] = 0;
//        $ext['msg_type'] = 9;

        //run
        $res = model('common/Noticle', 'logic')->sendCustomerServiceImg($file, $filename, $target, $ext);

        //return
        if ($res['code'] != SUCCESS) {
            echo json_encode(['code' => $res['code'], 'msg' => $res['msg']]);
            die;
        }
        echo json_encode(['code' => 0, 'msg' => '发送成功', 'data' => ['src' => $res['result']['url']]]);
        die;

    }


    public function audit()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id/d');
            $status = input('post.status/d');
            if (empty($id) || empty($status)) return json(['status' => 0, 'msg' => '缺少必要参数']);
            if (!in_array($status, [1, 2])) return json(['status' => 0, 'msg' => '审核状态错误']);

            $fileModel = model('common/member/File');
            $file = $fileModel->getInfoByID($id);
            if (empty($file)) return json(['status' => 0, 'msg' => '文件不存在']);
            if ($status == $file['status']) return json(['status' => 0, 'msg' => '状态未改变']);

            $res = $file->editByID($id, ['update_time' => time(), 'status' => $status, 'url' => config('app.fixed_image_path.sensitive_image')]);

            if ($res) {
                if ($file['url'] != config('app.fixed_image_path.sensitive_image')) model('common/file/FileLogic', 'logic')->deleteFile($file['url']);
                return json(['status' => 1, 'msg' => '操作成功']);
            }
            return json(['status' => 0, 'msg' => '操作失败']);
        }

    }

    public function setOneSelf()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id/d');
            $status = input('post.status/d',0);
            if (empty($id)) return json(['status' => 0, 'msg' => '缺少必要参数']);
            if (!in_array($status, [0, 1])) return json(['status' => 0, 'msg' => '参数错误']);

            $fileModel = model('common/member/File');
            $file = $fileModel->getInfoByID($id);
            if (empty($file)) return json(['status' => 0, 'msg' => '文件不存在']);
            if ($status == $file['is_oneself']) return json(['status' => 0, 'msg' => '状态未改变']);

            $res = $file->editByID($id, ['update_time' => time(), 'is_oneself' => $status]);
            return $res?json(['status' => 1, 'msg' => '操作成功']):json(['status' => 0, 'msg' => '操作失败']);
        }

    }
}